<?php

/**
 * Created by PhpStorm.
 * User: Lvyj
 * Date: 2017/6/29 0029
 * Time: 9:54
 */

namespace Admin\Assist\Service;

use Helpers\Main;
use Admin\Assist\Models\Assistance;
use Admin\Assist\Models\AssistanceCreateRequest;
use Admin\Assist\Models\CatalogInfo;
use Admin\Assist\Models\Client;
use Admin\Assist\Models\ClientFile;
use Admin\Assist\Models\Device;
use Admin\Assist\Models\Instruction;
use Admin\Assist\Models\Report;
use Admin\Assist\Models\Task;
use Admin\Assist\Models\User;
use Helpers\HttpClient;

class AssistService
{
    /**
     * 获取指令列表
     *
     * @param int $page
     * @param int $rows
     * @param string $keywords
     * @return array
     */
    public static function getInstructionList($page = 1, $rows = 10, $keywords = '')
    {
        //获取配置
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        //调用服务端接口
        $response = $httpClient->get("instructions", ['page' => $page, 'size' => $rows,
            'keywords' => $keywords]);
        $body = $response->toArray();
        $content = $body['content'];

        //数据转换
        $rows = array();
        foreach ($content as $index) {
            switch ($index['type']) {
                case 1:
                    $index['type'] = '诊断';
                    break;
                case 2:
                    $index['type'] = '修复';
                    break;
                default:
                    $index['type'] = '未知';
                    break;
            }
            array_push($rows, $index);
        }

        $data = [
            'total' => $body['totalElements'],
            'rows' => $rows
        ];
        return $data;
    }

    /**
     * 添加指令
     *
     * @param $content
     * @param null $name
     * @param null $description
     * @param string $type
     * @return string
     */
    public static function addInstruction($content, $name = null, $description = null, $type = '1')
    {
        $instruction = new Instruction();
        $instruction->content = $content;
        $instruction->name = $name;
        $instruction->description = $description;
        $instruction->type = intval($type);
        $json = json_encode($instruction);

        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setHeader('Content-Type', 'application/json');
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->post('instructions', $json);
        if ($response->isCreate()) {
            return '创建成功';
        }
        return '创建失败';
    }

    /**
     * 删除指令
     * @param string $idStr
     * @return string
     */
    public static function delInstruction($idStr = '')
    {

        $config = Main::getConfigByName("assist");
        $ids = explode(',', $idStr);
        //遍历删除
        foreach ($ids as $id) {
            $httpClient = new HttpClient();
            $httpClient->setBaseUrl($config['url']);
            $response = $httpClient->delete('instructions/' . $id);
            if (!$response->isSuccess()) {
                return '指令:' . $id . '删除失败';
            }
        }
        return '删除成功·';
    }

    /**
     * 获取协助列表
     *
     * @param int $page
     * @param int $rows
     * @param string $keywords
     * @return array
     */
    public static function getAssistanceList($page = 1, $rows = 10, $keywords = '')
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("assists", ['page' => $page,
            'size' => $rows,
            'keywords' => $keywords]);
        $body = $response->toArray();
        $content = $body['content'];
        //数据转换
        $rows = array();
        foreach ($content as $index) {
            $assistance = new Assistance();
            switch ($index['mode']) {
                case 1:
                    $assistance->mode = '服务端';
                    break;
                case 2:
                    $assistance->mode = '客户端';
                    break;
                default:
                    $assistance->mode = '未知';
                    break;
            }
            switch ($index['state']) {
                case 1:
                    $assistance->state = "准备";
                    break;
                case 3:
                    $assistance->state = '进行中';
                    break;
                case 4:
                    $assistance->state = '完成';
                    break;
                case 5:
                    $assistance->state = '超时';
                    break;
                default:
                    $assistance->state = '未知';
                    break;
            }

            //获取目标设备
            $assistance->deviceId = $index['target']['deviceId'];
            $assistance->userId = $index['target']['userId'];
            $assistance->userName = $index['target']['userName'];

            $assistance->name = $index['name'];
            $assistance->startAt = $index['startAt'];
            $assistance->endAt = $index['endAt'];
            $assistance->totalStep = $index['totalStep'];

            $href = \Phalcon\Di::getDefault()->get('url')->get("assist/assist/detail?id=" . $index['id']);
            //$href = "/assist/detail?id=" . $index['id'];
            $title = '协助详情';
            $url = 'javascript:window.top.xhTop.createNewTab("' . $title . '","' . $href . '")';
            $assistance->tasks = "<a class=\"btn btn-success\" target='' style='font-size: inherit' href=$url>任务详情</a>";
            array_push($rows, $assistance);
        }

        $data = [
            'total' => $body['totalElements'],
            'rows' => $rows
        ];

        return $data;
    }

    /**
     * 搜索用户
     *
     * @param int $page
     * @param int $rows
     * @param string $keywords
     * @return array
     */
    public static function searchUser($page = 1, $rows = 10, $keywords = '')
    {
        //调用user服务
        $config = Main::getConfigByName("user");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("api/v1/users/search", ['page' => $page, 'size' => $rows,
            'keywords' => $keywords]);
        $body = $response->toArray();
        //判断搜索到数据是否为空
        $content = null;
        $total = 0;
        if (!empty($body['content'])) {
            $content = $body['content'];
            $total = $body['totalElements'];
        } else if (empty($content)) {
            //id搜索
            $id = intval($keywords);
            if ($id > 0 && strlen($keywords) < 7) {
//                $http = new HttpClient();
//                $http->setBaseUrl($config['url']);
                $res = $httpClient->get("api/v1/users/" . $id);
                $content = array($res->toArray());
                $total = count($content);
            }
            //登录名搜索
            if (empty($content) && !empty($keywords)) {
//                $http = new HttpClient();
//                $http->setBaseUrl($config['url']);
                $res = $httpClient->get("api/v1/users/match?logonName=" . $keywords);
                $body = $res->toArray();
                if (!empty($body)) {
                    $content = array($body);
                    $total = count($content);
                }
            }
        }
        //数据转换
        $rows = array();
        foreach ($content as $index) {
            $user = new User();
            $user->name = $index['name'];
            $user->id = $index['id'];
            switch ($index['sex']) {
                case 1:
                    $user->sex = '男';
                    break;
                case 2:
                    $user->sex = '女';
                    break;
                default:
                    $user->sex = '未知';
                    break;
            }

            if (in_array('student', $index['roles'])) {
                $user->roles .= '学生 ';
            }
            if (in_array('teacher', $index['roles'])) {
                $user->roles .= '教师 ';
            }
            /*$href = "users/devices?id=" . $index['id'];
            $title = $index['name'] . "绑定设备列表";*/
            $href = "assist/users/clients?id=" . $index['id'];
            $title = $index['name'] . "注册客户端列表";
            $url = 'javascript:window.top.xhTop.createNewTab("' . $title . '","' . $href . '")';
            $user->userDevices = "<a class=\"btn btn-success\" target='_blank' style='font-size: inherit' href=$url>查看绑定设备</a>";
            array_push($rows, $user);
        }

        $data = [
            'total' => $total,
            'rows' => $rows
        ];
        return $data;
    }

    /**
     * 获取用户绑定设备
     *
     * @param int $id
     * @return array
     */
    public static function getUserDevices($id = 0)
    {

        $config = Main::getConfigByName("user");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $userId = $id;
        $response = $httpClient->get("api/v1/users/" . $userId . "/devices/");
        $content = $response->toArray();
        $total = count($content);
        $devices = array();
        foreach ($content as $item) {
            $device = new Device();
            $device->deviceId = $item['deviceId'];
            $device->os = $item['os'];
            $device->model = $item['model'];
            $device->activated = $item['activated'];
            $device->latitude = $item['latitude'];
            $device->longitude = $item['longitude'];
            $device->mac = $item['mac'];

            //$device->assist = "<button id='bt_assist_create' class=\"btn btn-success\" target='_blank' style='font-size: inherit'>发起协助</button>";
            array_push($devices, $device);
        }
        $data = [
            'total' => $total,
            'rows' => $devices
        ];

        return $data;
    }

    /**
     * 获取最近注册客户端
     *
     * @param int $id
     * @return array
     */
    public static function getUserClients($id = 0)
    {
        $config = Main::getConfigByName("user");
        $userId = $id;
        $appIds = array("zty_tea", "zty_stu");
        $clients = array();
        $total = 0;
        foreach ($appIds as $appId) {
            $httpClient = new HttpClient();
            $httpClient->setBaseUrl($config['url']);
            $response = $httpClient->get("api/v1/users/" . $userId . "/clients/recent?appId=" . $appId . "&providerId=TT");
            $content = $response->toArray();
            $total = $total + count($content);
            if (!empty($content)) {
                foreach ($content as $item) {
                    $client = new Client();
                    $client->deviceId = $item['deviceId'];
                    $client->appId = $item['appId'];
                    $client->clientId = $item['clientId'];
                    $client->providerId = $item['providerId'];
                    $client->registeredAt = date("Y-m-d H:i", $item['registeredAt']);

                    array_push($clients, $client);
                }
            }
        }
        $data = [
            'total' => $total,
            'rows' => $clients
        ];

        return $data;

    }

    /**
     * 获取用户信息
     * @param int $userId
     * @return User
     */
    public static function getUserInfo($userId = 0)
    {
        $config = Main::getConfigByName("user");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $idStr = $userId . '';
        $response = $httpClient->get("api/v1/users/?userIds=" . $idStr);
        $body = $response->toArray();
        $content = $body[0];
        $user = new User();
        $user->id = $content['id'];
        $user->name = $content['name'];
        switch ($content['sex']) {
            case 1:
                $user->sex = '男';
                break;
            case 2:
                $user->sex = '女';
                break;
            default:
                $user->sex = '未知';
                break;
        }
        if (in_array('student', $content['roles'])) {
            $user->roles .= '学生 ';
        }
        if (in_array('teacher', $content['roles'])) {
            $user->roles .= '教师 ';
        }
        return $user;
    }

    /**
     * 获取协助详情
     * @param null $assistanceId
     * @return array
     */
    public static function getAssistDetail($assistanceId = null)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("assists/" . $assistanceId);
        $content = $response->toArray();
        //$content = $httpClient->body;
        $tasks = $content['tasks'];
        $list = array();
        foreach ($tasks as $index) {
            $task = new Task();
            $task->id = $index['id'];
            $task->instruction = $index['instruction'];
            switch ($index['type']) {
                case 1:
                    $task->type = '诊断';
                    break;
                case 2:
                    $task->type = '修复';
                    break;
                default:
                    $task->type = '未知';
                    break;
            }
            switch ($index['state']) {
                case 1:
                    $task->state = '准备';
                    break;
                case 2:
                    $task->state = '收到指令';
                    break;
                case 3:
                    $task->state = '执行中';
                    break;
                case 4:
                    $task->state = '完成';
                    break;
                case 5:
                    $task->state = '超时';
                    break;
                case 6:
                    $task->state = '结果返回';
                    break;
                default:
                    $task->state = '未知';
                    break;
            }
            switch ($index['result']) {
                case 0:
                    $task->result = '未返回';
                    break;
                case 1:
                    $task->result = '执行成功';
                    break;
                case 2:
                    $task->result = '执行失败';
                    break;
                default:
                    $task->result = '未知';
                    break;
            }
            $task->step = $index['step'];
            $task->createAt = $index['createAt'];
            array_push($list, $task);
        }
        $data = [
            'total' => count($list),
            'rows' => $list
        ];
        return $data;
    }

    /**
     * 获取协助信息
     *
     * @param null $assistanceId
     * @return Assistance
     */
    public static function getAssistanceInfo($assistanceId = null)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("assists/" . $assistanceId);
        $index = $response->toArray();
        $assistance = new Assistance();
        switch ($index['mode']) {
            case 1:
                $assistance->mode = '服务端';
                break;
            case 2:
                $assistance->mode = '客户端';
                break;
            default:
                $assistance->mode = '未知';
                break;
        }
        switch ($index['state']) {
            case 1:
                $assistance->state = "准备";
                break;
            case 3:
                $assistance->state = '进行中';
                break;
            case 4:
                $assistance->state = '完成';
                break;
            case 5:
                $assistance->state = '超时';
                break;
            default:
                $assistance->state = '未知';
                break;
        }

        //获取目标设备
        $assistance->deviceId = $index['target']['deviceId'];
        $assistance->userId = $index['target']['userId'];
        $assistance->userName = $index['target']['userName'];

        $assistance->name = $index['name'];
        $assistance->startAt = $index['startAt'];
        $assistance->endAt = $index['endAt'];
        $assistance->totalStep = $index['totalStep'];
        return $assistance;
    }

    /**
     * 获取任务详情
     *
     * @param null $assistId
     * @param null $taskId
     * @return mixed
     */
    public static function getTaskDetail($assistId = null, $taskId = null)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("assists/" . $assistId . '/tasks/' . $taskId);
        $content = $response->toArray();
        $task = new Task();
        $task->id = $content['id'];
        $task->instruction = $content['instruction'];
        switch ($content['result']) {
            case 0:
                $task->result = '未执行';
                break;
            case 1:
                $task->result = '执行成功';
                break;
            case 2:
                $task->result = '执行失败';
                break;
            default:
                $task->result = "未知";
                break;
        }
        $resources = $content['resources'];
        if (isset($resources) && !empty($resources)) {
            foreach ($resources as $res) {
                switch ($res['fileType']) {
                    case 1:
                        $res['fileType'] = '图片';
                        break;
                    case 2:
                        $res['fileType'] = '日志';
                        break;
                    case 3:
                        $res['fileType'] = '文件';
                        break;
                    default:
                        $res['fileType'] = '未知';
                        break;
                }
            }
        }
        return $content;
    }

    /**
     * 发起协助
     * @param null $deviceId
     * @param int $userId
     * @param null $userName
     * @return string
     */
    public static function createAssist($deviceId = null, $userId = 0, $userName = null)
    {
        $assistance = new AssistanceCreateRequest();
        $assistance->userName = $userName;
        $assistance->userId = $userId;
        $assistance->deviceId = $deviceId;
        $assistance->mode = 1;
        $json = json_encode($assistance);

        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url'])
            ->setHeader('Content-Type', 'application/json')
            ->fullResponse();
        $response = $httpClient->post('assists', $json);
        if ($response->isSuccess()) {
            //获取头部uri
            $location = $response->responseHeader['Location'];
            $urlArray = explode('/', $location);
            $id = end($urlArray);
            return $id;
        }
        return null;
    }

    /**
     * 下发任务
     * @param $assistId
     * @param $type
     * @param $instruction
     * @return null|string
     */
    public static function distributeTask($assistId, $type, $instruction)
    {
        $task = new Task();
        //字符转换
        $task->instruction = htmlspecialchars_decode($instruction);
        $task->type = $type;
        $json = json_encode($task);

        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url'])
            ->setHeader('Content-Type', 'application/json')
            ->fullResponse();
        //$url='assists/' . $assistId . '/tasks';
        $url = 'assists/' . $assistId . '/tasks/distribute';
        $response = $httpClient->post($url, $json);
        if ($response->isSuccess()) {
            $location = $response->responseHeader['Location'];
            $urlArray = explode('/', $location);
            $taskId = end($urlArray);
            //任务执行
            //return self::executeTask($assistId, $taskId);
            //var_dump($taskId);die();
            return $taskId;
        }
        return null;
    }

    public static function executeTask($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->put('assists/' . $assistId . '/tasks/' . $taskId . '/execute');
        if ($response->isSuccess()) {
            return '下发成功';
        }
        return '下发失败';
    }

    /**
     * 退出
     *
     * @param $assistId
     * @return string
     */
    public static function quitAssistance($assistId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->put('/assists/' . $assistId . '/quit');
        if ($response->isSuccess()) {
            return '退出成功';
        }
        return '退出失败';
    }

    /**
     * 获取客户端协助请求
     *
     * @param int $page
     * @param int $rows
     * @param string $keywords
     * @return array
     */
    public static function getAssistRequest($page = 1, $rows = 10, $keywords = '')
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("assists/executing", ['page' => $page,
            'size' => $rows,
            'keywords' => $keywords]);
        $body = $response->toArray();
        $content = $body['content'];
        //数据转换
        $rows = array();
        foreach ($content as $index) {
            $assistance = new Assistance();
            switch ($index['mode']) {
                case 1:
                    $assistance->mode = '服务端';
                    break;
                case 2:
                    $assistance->mode = '客户端';
                    break;
                default:
                    $assistance->mode = '未知';
                    break;
            }
            switch ($index['state']) {
                case 1:
                    $assistance->state = "准备";
                    break;
                case 3:
                    $assistance->state = '进行中';
                    break;
                case 4:
                    $assistance->state = '完成';
                    break;
                case 5:
                    $assistance->state = '超时';
                    break;
                default:
                    $assistance->state = '未知';
                    break;
            }

            //获取目标设备
            $assistance->deviceId = $index['target']['deviceId'];
            $assistance->userId = $index['target']['userId'];
            $assistance->userName = $index['target']['userName'];

            $assistance->name = $index['name'];
            $assistance->startAt = $index['startAt'];
            $assistance->endAt = $index['endAt'];
            $assistance->totalStep = $index['totalStep'];
            $id = $index['id'];
            //$href = "/assistance/assist/detail?id=" . $index['id'];
            //$title = '任务详情';
            //$url = 'javascript:window.top.xhTop.createNewTab("' . $title . '","' . $href . '")';
            $url = 'javascript:agreeAssist(' . $id . ')';

            $assistance->tasks = "<a id='btn_agree' class=\"btn btn-success\" target='' style='font-size: inherit' href=$url>同意协助</a>";
            array_push($rows, $assistance);
        }

        $data = [
            'total' => $body['totalElements'],
            'rows' => $rows
        ];

        return $data;
    }

    /**
     * 同意协助请求
     *
     * @param $assistId
     * @return string
     */
    public static function agreeAssistRequest($assistId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->put('/assists/' . $assistId . '/agree');
        if ($response->isOk()) {
            return '进入协助';
        }
        return '操作失败';
    }

    /**
     * 获取协助是否存活
     * @param $assistId
     * @return
     */
    public static function getAssistAlive($assistId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get('/assists/' . $assistId . '/alive');
        return $response->header->statusCode;
    }

    /**
     * 获取目录
     * @param $assistId
     * @param $taskId
     * @return array
     */
    public static function getCatalogs($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/result");
        $body = $response->toArray();
        $content = $body['content'][0];
        $instruction = $body['instruction'];
        $rows = array();
        $num = 0;
        if (!empty($content) && !empty($instruction)) {
            //去除前缀
            $content = str_replace($instruction . ":", "", $content);
            //json
            $files = json_decode($content);
            $num = count($files);
            foreach ($files as $index) {
                $file = new ClientFile();
                $file->name = $index->name;
                $length=intval($index->length);
                $size=self::file_size_format($length);
                //$file->isFile = $index->isFile;
                if ($index->isFile) {
                    $src = \Phalcon\Di::getDefault()->get('url')->get('assist/img/file.png');
                    $file->fileType = "<img src='" . $src . "' width=\"15\">";
                    $file->isFile = 1;
                    $file->totalSpace=$size;
                } else {
                    $src = \Phalcon\Di::getDefault()->get('url')->get('assist/img/dir.png');
                    $file->fileType = "<img src='" . $src . "' width=\"15\">";
                    $eve = 'this';
                    $file->entry = "<button class='bt-catalog-entry btn btn-success' style='font-size:inherit' onclick='entryLineCatalog(" . $eve . ")'>进入</button>";
                    $file->isFile = 0;
                    $file->totalSpace=$size;
                }
                //$file->upload = "<a id='bt_catalog_upload' class=\"btn btn-success\" target='' style='font-size: inherit' href=''>上传</a>";
                array_push($rows, (array)$file);
            }
            $rows = self::arraySequence($rows, 'isFile');
        }
        //数据转换
        $data = [
            'total' => $num,
            'rows' => $rows
        ];

        return $data;
    }

    private static function file_size_format($size = 0, $dec = 2) {
        $unit = array("B", "KB", "MB", "GB", "TB", "PB");
        $pos = 0;
        while ($size >= 1024) {
            $size /= 1024;
            $pos++;
        }
        $result['size'] = round($size, $dec);
        $result['unit'] = $unit[$pos];
        return $result['size'].$result['unit'];
    }

    /**
     * @param $assistId
     * @param $taskId
     * @return CatalogInfo
     */
    public static function getAssistCatalogInfo($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/info");
        $body = $response->toArray();
        $catalog = new CatalogInfo();
        $path = str_replace("getFileTree(\"", "", $body['instruction']);
        $path = str_replace("\")", "", $path);
        $catalog->path = $path;
        $catalog->state = $body['state'];
        return $catalog;
    }

    public static function getTaskInfo($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/info");
        $body = $response->toArray();
        $catalog = new CatalogInfo();
        $catalog->state = $body['state'];
        $catalog->resources = $body['resources'];
        foreach ($catalog->resources as &$resource) {
            $resource['url'] = self::transformUrl($resource['url']);
        }
        unset($resource);
        return $catalog;
    }

    private static function arraySequence($array, $field, $sort = 'SORT_ASC')
    {
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }

    /**
     * 获取安装应用
     * @param $assistId
     * @param $taskId
     * @return array
     */
    public static function getInstalledApps($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/result");
        $body = $response->toArray();
        $content = $body['content'][0];
        $instruction = $body['instruction'];
        $rows = array();
        $num = 0;
        if (!empty($content) && !empty($instruction)) {
            //去除前缀
            $content = str_replace($instruction . ":", "", $content);
            //json
            $apps = json_decode($content);
            //print_r($apps);die();
            $num = count($apps);
            //处理应用列表
            /*foreach ($apps as $app) {

            }*/
            $rows = $apps;
            //排序
            $rows = self::arraySequence($rows, 'packageName', 'SORT_DESC');
        }
        //数据转换
        $data = [
            'total' => $num,
            'rows' => $rows
        ];

        return $data;
    }

    public static function getNetwork($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/result");
        $body = $response->toArray();
        $content = $body['content'][0];
        $instruction = $body['instruction'];
        if (!empty($content) && !empty($instruction)) {
            $content = str_replace($instruction . ":", "", $content);
            $network = json_decode($content);
            return $network;
        }
        return null;
    }

    public static function getSystem($assistId, $taskId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $response = $httpClient->get("/assists/" . $assistId . "/tasks/" . $taskId . "/result");
        $body = $response->toArray();
        $content = $body['content'][0];
        $instruction = $body['instruction'];
        if (!empty($content) && !empty($instruction)) {
            $content = str_replace($instruction . ":", "", $content);
            $network = json_decode($content);
            return $network;
        }
        return null;
    }

    /**
     * 获取报表列表
     * @param $page
     * @param $rows
     * @param $type
     * @param $userId
     * @param $deviceId
     * @return array
     */
    public static function getReports($page, $rows,$type,$userId,$deviceId)
    {
        $config = Main::getConfigByName("assist");
        $httpClient = new HttpClient();
        $httpClient->setBaseUrl($config['url']);
        $json=['page' => $page,
            'size' => $rows,
            'type'=>intval($type)
            ];
        if(!empty($userId)){
            $json['userId']=intval($userId);
        }
        if(!empty($deviceId)){
            $json['deviceId']=$deviceId;
        }
        $response = $httpClient->get("reports", $json);
        $body = $response->toArray();
        $reports = array();
        foreach ($body['content'] as $index) {
            $report = new Report();
            $report->id = $index['id'];
            $report->userId = $index['userId'];
            $report->deviceId = $index['deviceId'];
            $report->createAt = $index['createAt'];
            $report->packageName = $index['packageName'];
            switch ($index['type']) {
                case 0:
                    $report->type = '网络检测';
                    break;
                case 1:
                    $report->type = '日活检测';
                    break;
                case 2:
                    $report->type = '流量检测';
                    break;
                default:
                    $report->type = '未知';
                    break;
            }
            $report->url = '<a href="' . $index['url'] . ' ">' . $index['url'] . '</a>';
            array_push($reports, $report);
        }

        $data = [
            'total' => $body['totalElements'],
            'rows' => $reports
        ];

        return $data;
    }

    private static function transformUrl($url)
    {
        //以"http://oss-cn-hangzhou"开头的都需要处理//
        //http://oss-cn-hangzhou.aliyuncs.com/xhfs1/CA101005/c58e035edc354f5c89f646f9f98487ef.amr
        //http://xhfs1.oss-cn-hangzhou.aliyuncs.com/CA101005/c58e035edc354f5c89f646f9f98487ef.amr
        //http://xhfs3.oss-cn-hangzhou.aliyuncs.com/CA106002/e3321d80557a4938b118f3dff0647528.pptx
        if (self::startsWith($url, 'http://oss-cn-hangzhou') || self::startsWith($url, 'https://oss-cn-hangzhou')) {
            $url = str_replace('http://', '', $url);
            $url = str_replace('https://', '', $url);
            //转换为数组
            $tempArray = explode('/', $url);
            if (empty($tempArray) || count($tempArray) < 4 || $tempArray[1] == 'xuehaifile') {
                return $url;
            }
            $bucket = $tempArray[1];
            $url = 'http://' . $bucket . '.' . $tempArray[0] . '/' . $tempArray[2] . '/' . $tempArray[3];
        }
        return $url;
    }

    private static function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }
}